<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Koji</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="script/prototype.js"></script>
<script type="text/javascript">
var MBUSS = {
	map: null,
	terminalOrigem: null,
	terminalDestino: null,
	geocoder: new google.maps.Geocoder(),
	directionsRenderer: new google.maps.DirectionsRenderer({markerOptions: {draggable: false}}),
	init: function() {
		var latlng = new google.maps.LatLng(-23.6014, -46.6758);

		var mapOptions = {
		  zoom: 15,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		MBUSS.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

	},

	drawRoute: function(button) {
		var div = button.up(".input_canvas");

		var originAddress = div.down('.origin').value;
		var destinationAddress = div.down('.destination').value;

		var waypoints = [];
		$$('[name="ponto"]').each(function(p){
			if(p.value != '') {
				var way = {
					location: p.value,
					stopover: true
				}
				waypoints.push(way);
			}
		});

		MBUSS.geocoder.geocode({address:originAddress},
			function(e, s){
				MBUSS.terminalOrigem = e[0];
				MBUSS.geocoder.geocode({address:destinationAddress},
					function(e, s){
						MBUSS.terminalDestino = e[0];

						var directions = new google.maps.DirectionsService();

						var directionsRequest = {
							origin: MBUSS.terminalOrigem.geometry.location,
							destination: MBUSS.terminalDestino.geometry.location,
							travelMode: google.maps.DirectionsTravelMode.DRIVING,
							provideRouteAlternatives: false,
							waypoints: waypoints
						}
						directions.route(directionsRequest, function(result, status){
                                                        var pontolatitude = "";
                                                        var pontolongitude = "";
                                                        var pontoparada = ":true";
                                                        var trechodistancia = "";
                                                        var nomeponto = "";

                                                        result.routes[0].legs.each(function(leg){
                                                            pontolatitude += ":" + leg.start_location.lat();
                                                            pontolongitude += ":" + leg.start_location.lng();
                                                            trechodistancia += ":" + leg.distance.value;
                                                        });
                                                        pontolatitude += ":" + result.routes[0].legs.last().end_location.lat();
                                                        pontolongitude += ":" + result.routes[0].legs.last().end_location.lng();

                                                        $$('[name="nome-ponto"]').each(function(ponto){
                                                            nomeponto += ":" + ponto.getValue();
                                                        });
                                                        $$('[name="parada"]').each(function(parada){
                                                            pontoparada += ":"
                                                            if(parada.getValue() == 'on') {
                                                                pontoparada += "true";
                                                            } else {
                                                                pontoparada += "false";
                                                            }
                                                        });
                                                        pontoparada += ":true";

                                                        $('ponto-latitude').setValue(pontolatitude);
                                                        $('ponto-longitude').setValue(pontolongitude);
                                                        $('ponto-parada').setValue(pontoparada);
                                                        $('trecho-distancia').setValue(trechodistancia);
                                                        $('ponto-nome').setValue(nomeponto);
                                                    
							MBUSS.directionsRenderer.setMap(MBUSS.map);
							MBUSS.directionsRenderer.setDirections(result);
						});
					}
				);
			}
		);
	},

	insertPoint: function(span) {
		var row = span.up('tr');
		var table = span.up('table');

		var tr = table.insertRow(row.rowIndex+1);

		var thLabel = new Element('th');
		thLabel.innerHTML = 'Ponto';

		var tdInput = new Element('td');
		var tdId = tdInput.identify();
		tdInput.innerHTML = 'Nome: <input name="nome-ponto" /> <br /> Endere&ccedil;o: <input name="ponto" class="point address" ></input> <input type="button" onclick="javascript:MBUSS.removePoint('+"'"+tdId+"'"+');" value="X" />' +
                            '<br />Ponto de Parada: <input name="parada" type="checkbox" />';

		tr.appendChild(thLabel);
		tr.appendChild(tdInput);

		var tr2 = table.insertRow(row.rowIndex+2);

		var tdSpan = new Element('td');
		tdSpan.innerHTML = '<span class="empty" onclick="MBUSS.insertPoint(this);" ></span>';
		tdSpan.colSpan = '2';

		tr2.appendChild(tdSpan);
	},

	removePoint: function(tdId) {
		var tr = $(tdId).up('tr');
		var tr2 = tr.next('tr');

		tr.remove();
		tr2.remove();
	}
}

document.observe('dom:loaded', function() {MBUSS.init();});
</script>
<style type="text/css">
.origin, .destination {
	width: 100%;
}

.address {
	min-width: 250px;
}

.label, .field {
	display: inline;
}

.empty {
	display: inline-block;
	height: 15px;
	width: 100%;
	cursor: pointer;
}

.empty:hover {
	background-color: #DADADA;
}

.input_canvas {
	width: 600px;
	float:left;
	font-size: 10pt;
}

.input_canvas > table {
	width: 100%;
	font-size: 10pt;
}

.input_canvas > table > tr,.input_canvas > table > td {
	width: 100%;
}
</style>
</head>
<body>
<div id="input_canvas" class="input_canvas">
        <fieldset>
	<table>
		<tr>
			<th>Terminal Inicial</th>
			<td>
                            Nome: <input name="nome-ponto" value="Ponto 1" />
                            <br />
                            Endere&ccedil;o: <input id="origin" class="origin address" name="origin" value="R. Dom Pero Leitao, 153 - Sao Paulo SP" />
                        </td>
		</tr>
		<tr>
			<td colspan="2"><span class="empty" onclick="MBUSS.insertPoint(this);" ></span></td>
		</tr>
		<tr>
			<th>Ponto</th>
			<td>
                            Nome: <input name="nome-ponto" value="Ponto 2" />
                            <br />
                            Endere&ccedil;o: <input name="ponto" class="point address" value="R. Padre Machado - Sao Paulo SP" /> <input type="button" onclick="javascript:MBUSS.removePoint('');" value="X" />
                            <br />
                            Ponto de Parada: <input name="parada" type="checkbox" />
                        </td>
		</tr>
		<tr>
			<td colspan="2"><span class="empty" onclick="MBUSS.insertPoint(this);" ></span></td>
		</tr>
		<tr>
			<th>Ponto</th>
			<td>
                            Nome: <input name="nome-ponto" value="Ponto 3" />
                            <br />
                            Endere&ccedil;o: <input name="ponto" class="point address" value="R. Sena Madureira - Sao Paulo SP" /> <input type="button" onclick="javascript:MBUSS.removePoint('');" value="X" />
                            <br />
                            Ponto de Parada: <input name="parada" type="checkbox" />
                        </td>
		</tr>
		<tr>
			<td colspan="2"><span class="empty" onclick="MBUSS.insertPoint(this);" ></span></td>
		</tr>
		<tr>
			<th>Terminal Final</th>
			<td>
                            Nome: <input name="nome-ponto" value="Ponto Final" />
                            <br />
                            Endere&ccedil;o: <input id="destination" class="destination address" name="destination" value="R. Gomes de Carvalho, 209 - Sao Paulo SP" />
                        </td>
		</tr>
	</table>
	<hr/>
	<input type="button" value="Gerar Rota" onclick="MBUSS.drawRoute(this);" />
        </fieldset>
        <fieldset>
            <form action="GMaps.action" method="post" >
                <div id="resultado">
                    Nome Linha: <input name="linha-nome" id="linha-nome" />
                    <br />
                    <br />
                    Nomes pontos: <input name="ponto-nome" id="ponto-nome" />
                    <br />
                    <br />
                    Pontos X: <input name="ponto-latitude" id="ponto-latitude" />
                    <br />
                    Pontos Y: <input name="ponto-longitude" id="ponto-longitude" />
                    <br />
                    Pontos de Parada: <input name="ponto-parada" id="ponto-parada" />
                    <br />
                    <br />
                    Dist&acirc;ncias: <input name="trecho-distancia" id="trecho-distancia" />
                    <br />
                    <br />
                    N&ordm; de &Ocirc;nibus: <input name="numero-onibus" id="numero-onibus" />
                    <br />
                    <hr />
                    <br />
                    <input type="hidden" name="op" value="true" />
                    <input type="submit" value="Criar Linha" />
                </div>
            </form>
        </fieldset>
</div>
<div id="map_canvas" style="width: 50%; height: 700px;"><!-- nada --></div>

</body>
</html>